<?php
namespace App\Helpers;

// | Author: yunwuxin <478053684@qq.com>
// +----------------------------------------------------------------------

class commonFuc {


    /**api借口数据 转换返回json
     * @param unknown $data
     * @param int $code
     * @param string $messge
     * @return Json
     */
    static function data_reture_json($data=[],$code=200,$message=''){
        if(isset($GLOBALS['isjson']) && !$GLOBALS['isjson'])return $data;
        return  response(json_encode(array(
            'code'=>(int)$code,
            'data'=>$data,
            'message'=>(string)$message
        )),200,['Content-Type'=>'application/json; charset=utf-8']);

    }

    /**api借口数据 转换返回json 并且结束
     * @param unknown $data
     * @param int $code
     * @param string $messge
     * @return Json
     */
    static function data_reture_json_exit($data=[],$code=200,$message=''){
        if(isset($GLOBALS['isjson']) && !$GLOBALS['isjson'])return $data;
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode(array(
            'code'=>(int)$code,
            'data'=>$data,
            'message'=>(string)$message
        )));
    }

    /**api请求日志
     * @param false $return_data
     */
    static function apiLog($return_data=false,$dirname='apilog'){
        $SERVER_NAME=isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'';
        $REQUEST_URI=isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'';
        $REQUEST_SCHEME=isset($_SERVER['REQUEST_SCHEME'])?$_SERVER['REQUEST_SCHEME']:'http';
        $log=[
            //'SERVER_NAME'=>$SERVER_NAME,
            'INPUT_Headers'=>getallheaders(),

            'REQUEST_URI'=>$REQUEST_URI,
            'URL'=>$REQUEST_SCHEME.'://'.$SERVER_NAME.$REQUEST_URI,

        ];
        $log['INPUT_params']=[];
        if(isset($_REQUEST))$log['INPUT_params']=$_REQUEST;
        $params=[];
        foreach ($log['INPUT_params'] as $key=>$param){
            if($key!='s'){
                $params[]="$key=$param";
            }
        }
        $log['test_url']=explode('?',$log['URL'])[0].'?'.join('&',$params);

        $REQUEST_URI_s=explode('?',$REQUEST_URI)[0];
        $REQUEST_URI_s=str_replace('/','-',$REQUEST_URI_s);
        $titls='start';
        if($return_data){
            $log=$return_data;
            $log['return_json']="\r\n".json_encode($return_data)."\r\n\r\n";
            $titls='return-end';
        }
        $titls.='  '.self::getip();
        self::dump($log,true,$titls,$REQUEST_URI_s.'.log','logdump/'.$dirname.'/'.date('Y-m-d').'/');

        if(isset($_REQUEST['debug']) && $_REQUEST['debug']==1) self::dump($log);
    }
    static function dump($msg,$write=false,$title='',$path='',$dir='logdump/'){
        $time=date('Y-m-d H:i:s');
        $fg='+ + + + + + +';
        $fgh='_ _ _ _ _ _ _';
        $title2=" $fgh  $title  $time  $fgh \r\n";
        $title1="\r\n $fg  $title  $time  $fg \r\n";

        if(!$write){
            echo '<pre>';
            echo $title1;
            print_r($msg);
            echo $title2;
            return;
        }
        ob_start();
        print_r($msg);
        $msg = ob_get_clean();

        $msg  = $title1. $msg . $title2;
        $dir=$dir?$dir:('logdump/');
        $root=isset($_SERVER['DOCUMENT_ROOT'])?$_SERVER['DOCUMENT_ROOT'].'/':'./';
        $dir=$root.$dir;
        if(!is_dir($dir)){
            mkdir(iconv("UTF-8", "GBK", $dir),0777,true);
        }
        $path = $dir.($path?$path:date('Ymd').'_dump.log');
        file_put_contents($path, $msg, FILE_APPEND);
        // echo "\n".$time.'=>CommFun::dump()=>write=>'.$path. "\n";

    }
    /**
     * desription 判断是否gif动画
     * @param sting $image_file图片路径
     * @return boolean t 是 f 否
     */
   private static function check_gifcartoon($image_file){
        $fp = fopen($image_file,'rb');
        $image_head = fread($fp,1024);
        fclose($fp);
        return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
    }
    /**
     * desription 压缩图片
     * @param sting $imgsrc 图片路径
     * @param string $imgdst 压缩后保存路径
     * @param string $zipv=95 压缩保真度
     */
    static  function image_png_size_add($imgsrc,$imgdst,$zipv=95){
        list($width,$height,$type)=getimagesize($imgsrc);
        $bl=$width/$height;
        $new_width = ($width>800?800:$width)*0.9;
        $new_height =$new_width/$bl;
        switch($type){
            case 1:
                $giftype=self::check_gifcartoon($imgsrc);
                if($giftype){
                    header('Content-Type:image/gif');
                    $image_wp=imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    imagejpeg($image_wp, $imgdst,$zipv);
                    imagedestroy($image_wp);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_wp, $imgdst,$zipv);
                imagedestroy($image_wp);
                break;
            case 3:
                header('Content-Type:image/png');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_wp, $imgdst,$zipv);
                imagedestroy($image_wp);
                break;
        }
    }
  static  function getip() {
        static $ip = '';
        $ip = $_SERVER['REMOTE_ADDR'];
        if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
            $ip = $_SERVER['HTTP_CDN_SRC_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] AS $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }
    /**检查RUL是否有http 返回正确的地址
     * @param $url
     * @return mixed
     */
    static function check_img_url($url,$dalurl=''){
        if($url=='' && $dalurl!=='')$url=$dalurl;
        if(!strpos('jkw_'.$url,"http:") && !strpos('jkw_'.$url,"https:")) {
            if (isset($_SERVER['REQUEST_SCHEME'])) {
                $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER["HTTP_HOST"] . $url;
            } else {
                $url = 'http://' . $_SERVER["HTTP_HOST"] . $url;
            }
        }
        return $url;
    }

    /**
     * redis存
     * @param unknown $name
     * @param unknown $value
     * @param unknown $time
     * @return boolean|mixed
     */
    static function redis($key,$value='',$time=0){
        $redis= new \Redis();

        //$redis->connect('127.0.0.1',6379);
        $redis->connect('122.51.85.249',6379);
        $redis->auth('1toyw08oiu.84'); //密码验证

        $key=strlen($key)>32?md5($key):$key;

        if($value==''){
            $result = $redis->get(getenv('REDIS_PREFIX').$key);
            return is_null(json_decode($result))?$result:json_decode($result,true);
        }else{
            if($value=='_del'){
                return  $redis->del($key);
            }else{
                $value = is_array($value)?json_encode($value):$value;
                return $time>0?$redis->setex(getenv('REDIS_PREFIX').$key, $time,$value):$redis->set(getenv('REDIS_PREFIX').$key,$value);
            }

        }

    }

    /**
     * redis存队列  第一个添加，获取最后一个
     * @param unknown $name
     * @param unknown $value
     * @return boolean|mixed
     */
    static function redisPushPop($name,$value=''){
        $isredis= new \Redis();
        $isredis->connect('127.0.0.1',6379);
        // $isredis->auth('12345'); //密码验证

        if($value){
            $isredis->lPush($name,$value);
        }else{
            return $isredis->rpop($name);
        }

    }
    /**
     *本段代码由老修提供, 转载请备注出处 www.lao8.org
     *调用方式比较简单: echo getcontent($url); 可以抓取网页/也可以抓取图片
     *批量抓取的时候用file_get_contents可能会飙升服务器cpu和内存, 而 curl方式则不会, 而且还可以伪装马甲防止批量抓取被发现封ip.
     */
   static  function getcontent($weburl,$header=[]){
       $data='';
       if(strpos('pp_'.$weburl,"https:")){

           $curl = curl_init(); // 启动一个CURL会话
           curl_setopt($curl, CURLOPT_URL, $weburl);
           curl_setopt($curl, CURLOPT_HEADER, 0);
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在  只有在cURL低于7.28.1时CURLOPT_SSL_VERIFYHOST才支持使用1
         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
           $data = curl_exec($curl);     //返回api的json对象
           //关闭URL请求
           curl_close($curl);

       }else if(strpos('pp_'.$weburl,"http:")){

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $weburl);
        curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');//伪装一个来路
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) '); //伪装成百度蜘蛛
           curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
       /* curl_setopt($curl, CURLOPT_FOLLOWLOCATION,2); //抓取转跳*/
		if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 抓取转跳
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true) ;
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate'); //gzip解压
        curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
        $data = curl_exec($curl);
        // $infos = (curl_getinfo($curl));//返回抓取网页参数的值(数组);
        curl_close($curl);


          if(!$data){
         $data=file_get_contents($weburl);
          }
       }

        return $data;


    }

    /**取两日期间的所有日期
     * @param $date1  2005-02-01
     * @param $date2  2005-02-05
     *@return array date
     */

   static function getDateBetween($date1,$date2){ // 两个日期之间的所有日期
        $dt_start = strtotime($date1);
        $dt_end = strtotime($date2);
        while ($dt_start<=$dt_end){
            $data[]= date('Y-m-d',$dt_start);
            $dt_start = strtotime('+1 day',$dt_start);
        }
        return $data;
    }
    /**取文本中间文本
     * @param $left
     * @param $right
     * @param $content
     *@return array string
     */

    static function getStringBetween($left,$right,$content){

       if($left){
           $l1=explode($left, $content);
           unset($l1[0]);
           $content=join($left,$l1);
       }
       if($right){
           $l1=explode($right, $content);
           $content=$l1[0];
       }
        return $content;
	}

    /**
     * 删除一个目录 或者 文件
     * 包括子目录和所有文件
     * @param $dir
     * @return bool
     */
  static  function deleFileOrDir($dir){
        if(is_dir($dir)){
            foreach(scandir($dir) as $row){
                if($row == '.' || $row == '..'){
                    continue;
                }
                $path = $dir .'/'. $row;
                self::deleFileOrDir($path);
            }
            rmdir($dir);
        }else{
            if(!file_exists($dir)){
                return false;
            }
            if(PATH_SEPARATOR == ':'){ //linux
                unlink($dir);
            }else{  //Windows
                $url=iconv('utf-8','gbk',$dir);
                unlink($url);
            }

        }
      return true;
    }
    static function decrypt($jsonstring, $key = '')
    {
        $key = md5(empty ($key) ? 'niucloud098)(*' : $key);
        $data = str_replace(array (
            '-',
            '_'
        ), array (
            '+',
            '/'
        ), $jsonstring);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        $data = base64_decode($data);
        $expire = substr($data, 0, 10);
        $data = substr($data, 10);

        if ($expire > 0 && $expire < time()) {
            return '';
        }
        $x = 0;
        $len = strlen($data);
        $l = strlen($key);
        $char = $str = '';

        for ($i = 0; $i < $len; $i++) {
            if ($x == $l)
                $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }

        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
                $str .= chr(( ord(substr($data, $i, 1)) + 256 ) - ord(substr($char, $i, 1)));
            } else {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return base64_decode($str);
    }

    /**加密
     * @param $data
     * @param string $key
     * @param int $expire
     * @return string|string[]
     */
    static function encrypt($jsonstring, $key = '', $expire = 0)
    {
        $key = md5(empty ($key) ? 'niucloud098)(*' : $key);

        $data = base64_encode($jsonstring);
        $x = 0;
        $len = strlen($data);
        $l = strlen($key);
        $char = '';

        for ($i = 0; $i < $len; $i++) {
            if ($x == $l)
                $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }

        $str = sprintf('%010d', $expire ? $expire + time() : 0);

        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord(substr($data, $i, 1)) + ( ord(substr($char, $i, 1)) ) % 256);
        }
        return str_replace(array (
            '+',
            '/',
            '='
        ), array (
            '-',
            '_',
            ''
        ), base64_encode($str));
    }
    /**
     * 下载html png 网站资源 包括用来生成静态html页面
     * @param $url
     * @param $url  url 链接
     * @param $file 保存的文件名  如public/1.html
     * @param $timeout 超时时间
     * @return bool
     */
    static function httpFileCopy($url, $file="", $timeout=60) {
        // set_time_limit(0);//设置超时时间 不限时
        $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
        $dir = pathinfo($file,PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir,0755,true);
        $url = str_replace(" ","%20",$url);

        if(function_exists('curl_init')) {
            echo "curl ";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $temp = curl_exec($ch);
            if(@file_put_contents($file, $temp) && !curl_error($ch)) {
                return $file;
            } else {
                return false;
            }
        } else {
            echo "copy ";
            $opts = array(
                "http"=>array(
                    "method"=>"GET",
                    "header"=>"",
                    "timeout"=>$timeout)
            );
            $context = stream_context_create($opts);
            if(@copy($url, $file, $context)) {
                //$http_response_header
                return $file;
            } else {
                return false;
            }
        }
    }


    /** 毫秒级时间戳
     * @return float
     */
    static function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
    /** 毫秒级时间戳
     * @return float
     */
    static function getMillisecond_echo($time=0,$title='') {
        $time_now=self::getMillisecond();
        echo '【';
        if($title)echo $title.' ';
        if($time==0){
            echo 0;
        }else{
            echo ($time_now-$time)/1000;

        }
        echo '秒】';
       return $time_now;
    }


    /*$string 要加密/解密的字符串
$code 秘钥字符串
$operation 默认false表示加密，传入true表示解密
*/
   static function DianJin_decode($string,$code,$operation=false){
        $code = md5(md5($code));
        $iv = substr($code,0,16);
        $key = substr($code,16);
        if($operation){
            return openssl_decrypt(base64_decode($string),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
        }
        return base64_encode(openssl_encrypt($string,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));

    }

    /**php 加密 js 直接写出
     * @param $string
     * @return string
     */
    static function DianJin_decode_script_write($string){
        $DianJin_decode=time()*4;
        return  "<script>DianJin_decode_write('".self::DianJin_decode($string,$DianJin_decode)."','".$DianJin_decode."');</script>";

    }

    /*
     *  生成随机字符串
     *
     *   $length    字符串长度
     */
    static  function random_str($length) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for($i = 0; $i < $length; $i++)
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
//            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    /**前面补零0
     * @param $str
     * @param $length
     */
    static function add0($str,$length){
        return substr('00000000000'.$str,-$length);
    }



    /**
     * 数组 转 对象
     *
     * @param array $arr 数组
     * @return object
     */
    static function array_to_object($arr) {
        if (gettype($arr) != 'array') {
            return;
        }
        foreach ($arr as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object') {
                $arr[$k] = (object)self::array_to_object($v);
            }
        }

        return (object)$arr;
    }


    /**
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    static  function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)self::object_to_array($v);
            }
        }

        return $obj;
    }

            /**检测是否日期格式
             * @param $date
             * @param string $format
             * @return bool
             */
        static function cheskIsDateTime($date,$format='Ymd'){
                return date($format,strtotime($date))==$date?true:false;
        }

    /**批量更新 或插入新数据 （如果存在为更新，不存在为插入）一定要更新相同的字段
     * @param $table  表名
     * @param $datas  要更新的数据数组
     * @param string $key_id  唯一字段名如：id
     * @param string $notnull  表中不能为空的字段名 多个,号分割 默认值为0
     * @return string|void    返回sql 语句  用  Db::query($sql)  可执行
      */
  static  function insert_into_on_duplicate_key_update_sql($table,$datas,$key_id='id',$notnull=''){
        if(count($datas)==0){
            return;
        }

        $notnulls=explode(',',$notnull);
        $table_key_notnulls=array_filter(array_merge(array_keys($datas[0]),$notnulls));
        $table_key='`'.join('`,`',$table_key_notnulls).'`';
        $duplicates=[];
        foreach ($datas[0] as $key_i=>$data1){
            if($key_id!==$key_i){
                if(substr($data1,0,2)=='=>'){
                    $duplicates[]=$key_i.'='.substr($data1,2);
                }else{
                    $duplicates[]=$key_i.'=values('.$key_i.')';
                }

            }

        }
        $table_key_valuekey=join(',',$duplicates);


        $values=[];

        foreach ($datas as $key=>$data){
            $data_values=[];
            foreach ($table_key_notnulls as $key_i){
                if(isset($data[$key_i])){
                    $data1=$data[$key_i];
                    if(!is_string($data1)){
                        $data_values[]=$data1;
                    }else{
                        if(substr($data1,0,2)=='=>'){
                            $data_values[]=0;
                        }else{
                            $data_values[]="'".$data1."'";
                        }
                    }
                }else{
                    $data_values[]=0;
                }


            }

            $values[]='  ('.join(',',array_values($data_values)).')';

        }
        $valuers=join(',',$values);


        //insert into sl_users_plans_txffc (`id`,`periods`,`content`) values (207985835,6) on duplicate key update periods=values(periods)
        return $sql="insert into $table ($table_key) values $valuers on duplicate key update $table_key_valuekey";

        // $datkk=Db::query($sql);

    }




    /**将数据库里面菜单数据转换为分类数据
     * @param null $ismenu
     * @param null $ids
     * @return array
     */
    static  function menusDb_to_children_menus($list){

        $menus_lspid=[];
        $menus_0=[];
        foreach ($list as $list1){
            $list1 = self::object_to_array($list1);
            $list1['spread']=true;//前台树形是否展开
            if($list1['pid']>0){
                if(!isset($menus_lspid[$list1['pid']])){
                    $menus_lspid[$list1['pid']]=[];
                }
                $menus_lspid[$list1['pid']][]=$list1;
            }else{
                $menus_0[]=$list1;
            }
        }

        foreach ($menus_0 as $key=>$menus_01) {
            $menus_0[$key]=self::whilemenus($menus_lspid,$menus_01);
        }
        return $menus_0;
    }
    /**树形菜单转换 menusDb_to_children_menus 私有
     * @param $menus_lspid
     * @param $data
     * @return mixed
     */
    private static function whilemenus($menus_lspid,$data){
        $data['children']=[];
        if(isset($menus_lspid[$data['id']])){

            foreach ($menus_lspid[$data['id']] as $key=>$menus_01) {


                $menus_01['children']=[];
                $data['children'][]=self::whilemenus($menus_lspid,$menus_01);
            }
        }
        return $data;

    }


}
